package com.example.luyennghe;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.ArrayList;
import java.util.List;

import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class DsBaiNgheActivity extends Activity{
    private UserInfo user = new UserInfo();
    private BaiNghe baiNghe;    
    Bundle extras;
    private ArrayList<String> baingheSaved = new ArrayList<String>();
    private ProgressDialog pDialog;
    private JSONParser jParser = new JSONParser();
    private ArrayList<BaiNghe> baiNgheArraylist;
    //private ArrayList<HashMap<String, String>> arraylistUserdata;
    private static String urlDsBainghe = "http://huynh.cu.cc/android-server/get_ds_bainghe.php";
    private static String urlUserData = "http://huynh.cu.cc/android-server/get_userdata.php";
    private static String urlAddRemoveBookmark = "http://huynh.cu.cc/android-server/bookmark.php";
    private String urlDownload = "http://www.fileden.com/files/2012/12/7/3374222/";
    private String url = "";
    private String capdo = "";
    private String bookmark = "";
    private int clickedIndex = 0;       //stt item o vi tri duoc click trong listview
    private String  filePath;
    public static final int DIALOG_DOWNLOAD_PROGRESS = 0;
    private final int TIMEOUT_CONNECTION = 50000;//50sec
    private final int TIMEOUT_SOCKET = 50000;//50sec
    private ProgressDialog mProgressDialog;
    private String path = Environment.getExternalStorageDirectory().toString() + "/bainghe/";
    
    
    private boolean insertedBookmarkSuccess = false;
    private boolean deletedBookmarkSuccess = false;
    private boolean errorConnectDatabase = false;
    private boolean noLessonFound = false;
    private boolean loadDsSuccess = false;
    
    JSONArray dsbainghe = new JSONArray();
    //JSON node
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_MESSAGE = "message";
    private static final String TAG_DSBAINGHE = "dsbainghe";
    private static final String TAG_ID = "id";
    private static final String TAG_STT = "stt";
    private static final String TAG_CAPDO = "capdo";
    private static final String TAG_TENBAINGHE = "tenbainghe";
    private static final String TAG_FILEPATH = "filepath";      

    private static final String TAG_USERDATA = "userdata";
    private static final String TAG_BOOKMARK = "bookmark";
    private static final String TAG_DALAM = "dalam";
    private static final String TAG_DIEM = "diem";
    private static final String TAG_NGAYLAM = "ngaylam";
    public ListView lv;
    
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.dsbainghe_layout);
        baiNgheArraylist = new ArrayList<BaiNghe>();
        lv = (ListView)findViewById(R.id.list);
        //lay thong tin user        
        extras = getIntent().getExtras();
        if (extras != null) {
            user = (UserInfo)extras.getSerializable("userinfo");
            capdo = extras.getString("capdo");
            Log.d("capdo: ", capdo);            
        }
        else
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DsBaiNgheActivity.this);
            builder.setTitle("Lỗi")
                    .setMessage("Có lỗi xảy ra. Hãy thử lại sau.")
                    .setCancelable(false)
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }        
        if (!checkInternetConnection()) {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DsBaiNgheActivity.this);
            builder.setTitle("Lỗi")
                    .setMessage("Không có kết nối internet. Hãy thử lại sau.")
                    .setCancelable(false)
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                    finish();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }       
        
        listFileSaved(capdo);
        Log.d("list save: ", baingheSaved.toString());
        //tải danh sách bài nghe
        loadBaingheHandler();
    }
    
    //lay danh sach cac file mp3 da tai ve trong may
    public void listFileSaved(String capdo){
        File fd = new File(path, capdo);
        for (File f : fd.listFiles()) {
            if (f.isFile()&&f.getName().endsWith(".mp3")){              
                baingheSaved.add(f.getName());
            }    
        }
    }
    
    //kiem tra bai nghe co ton tai trong may chua
    public Boolean baingheTonTai(String tenbainghe){
        File file = new File(path + capdo + "/", tenbainghe);
        if (file.exists()) {
          return true;
        }
        return false;
    }

    // kiểm tra kết nối internet
    private boolean checkInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo[] netInfo = cm.getAllNetworkInfo();
        // kiểm tra kết nối wifi và mobile(3G)
        for (NetworkInfo ni : netInfo) {
            if (ni.getTypeName().equalsIgnoreCase("WIFI"))
                if (ni.isConnected())
                    return true;
            if (ni.getTypeName().equalsIgnoreCase("MOBILE"))
                if (ni.isConnected())
                    return true;
        }
        if (cm.getActiveNetworkInfo() != null
                && cm.getActiveNetworkInfo().isAvailable()
                && cm.getActiveNetworkInfo().isConnected()) {
            return true;
        }
        return false;
    }

    
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case DIALOG_DOWNLOAD_PROGRESS:
            mProgressDialog = new ProgressDialog(DsBaiNgheActivity.this);
            mProgressDialog.setIcon(R.drawable.download_icon);
            mProgressDialog.setMessage("Downloading file " + filePath);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.setCancelable(true);
            mProgressDialog.show();
            return mProgressDialog;
        default:
            return null;
        }
    }
    //download file su dung asynctask
    class DownloadFileAsync extends AsyncTask<String, String, String> {

        private boolean running = true;

        @Override
        protected void onCancelled() {
            // TODO Auto-generated method stub
            running = false;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            mProgressDialog = new ProgressDialog(DsBaiNgheActivity.this);
            mProgressDialog.setTitle("Xin đợi trong giây lát...");
            mProgressDialog.setIcon(R.drawable.download_icon);
            mProgressDialog.setMessage("Downloading file " + filePath);
            mProgressDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            mProgressDialog.show();         
        }
        @Override
        protected String doInBackground(String... aurl) {
            if (running) {
                int count;

                try {

                    URL url = new URL(aurl[0]);
                    
                    URLConnection connection = url.openConnection();
                    connection.setReadTimeout(TIMEOUT_CONNECTION);
                    connection.setConnectTimeout(TIMEOUT_SOCKET);
                    connection.connect();
                    Log.d("ANDRO_ASYNC", "url: " + url);
                    // lấy dung lượng file
                    int lenghtOfFile = connection.getContentLength();
                    Log.d("ANDRO_ASYNC", "Lenght of file: " + lenghtOfFile);

                    InputStream input = new BufferedInputStream(
                            url.openStream());
                    OutputStream output = new FileOutputStream(path + capdo + "/" + filePath);

                    byte data[] = new byte[1024];

                    long total = 0;

                    while ((count = input.read(data)) != -1) {
                        total += count;
                        publishProgress(""
                                + (int) ((total * 100) / lenghtOfFile));
                        output.write(data, 0, count);
                    }

                    output.flush();
                    output.close();
                    input.close();
                } catch (Exception e) {
                }
            }
            return null;
        }

        protected void onProgressUpdate(String... progress) {
            Log.d("ANDRO_ASYNC", progress[0]);
            mProgressDialog.setProgress(Integer.parseInt(progress[0]));
        }

        @Override
        protected void onPostExecute(String unused) {
            mProgressDialog.dismiss();
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DsBaiNgheActivity.this);
            builder.setTitle("Thông báo")
                    .setMessage("Đã download xong file " + filePath)
                    .setCancelable(false)
                    .setIcon(R.drawable.ok_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                    View v = lv.getChildAt(clickedIndex - lv.getFirstVisiblePosition());
                                    ImageButton imgSave = (ImageButton)v.findViewById(R.id.imgSave);
                                    imgSave.setVisibility(View.VISIBLE);                                    
                                    /*// Starting new intent
                                    Intent in = new Intent(getApplicationContext(),
                                            nghe_activity.class);
                                    // sending data to next activity
                                    in.putExtra(TAG_filePath, path + filePath);
                                    in.putExtra("bainghe", _bainghe);
                                    in.putExtra("userinfo", user);
                                    startActivity(in);*/
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }
    }
    public class BaingheAdapter extends ArrayAdapter<BaiNghe>{
        String yes = "yes";
        BaiNghe bainghe = null;
        Context context;
        int layoutResourceId;   
        ArrayList<BaiNghe> data = null;
        
       
        public BaingheAdapter(Context context, int layoutResourceId, ArrayList<BaiNghe> data) {
            super(context, layoutResourceId, data);
            this.layoutResourceId = layoutResourceId;
            this.context = context;
            this.data = data;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View row = convertView;
            bainghe = data.get(position);
            BaingheHolder holder = null;
           
            if(row == null)
            {
                LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
                row = inflater.inflate(layoutResourceId, parent, false);
               
                holder = new BaingheHolder();
                holder.llBox = (LinearLayout)row.findViewById(R.id.llBox);
                holder.imgSave = (ImageButton)row.findViewById(R.id.imgSave);
                holder.tvDiem = (TextView)row.findViewById(R.id.tvDiem);
                holder.stt = (TextView)row.findViewById(R.id.stt);
                holder.tvNgaylam = (TextView)row.findViewById(R.id.tvNgaylam);
                holder.tenbainghe = (TextView)row.findViewById(R.id.tenbainghe);
                holder.imgBookmark = (ImageButton)row.findViewById(R.id.imgBookmark);
                holder.imgDalam = (ImageButton)row.findViewById(R.id.imgDalam);  
                //dat tag la position (index item)
                holder.imgBookmark.setTag(position);
                holder.llBox.setTag(position);
                //dat tag la id bai nghe
                holder.imgSave.setTag(bainghe.getId());
                row.setTag(holder);
            }
            else
            {
                holder = (BaingheHolder)row.getTag();
            }     
            if(yes.equals(bainghe.getBookmark())){
                holder.imgBookmark.setBackgroundResource(R.drawable.bookmarked);
                Log.d("--ten bai nghe so sanh: ", bainghe.getFilePath());
            }
            else    
                holder.imgBookmark.setBackgroundResource(R.drawable.none_bookmark);
            if(yes.equals(bainghe.getDaLam())){
                holder.imgDalam.setVisibility(View.VISIBLE);
                holder.tvDiem.setText(bainghe.getDiem() + " điểm");
                holder.tvNgaylam.setText("Vào lúc " + bainghe.getNgayLam());
                holder.tvDiem.setVisibility(View.VISIBLE);
                holder.tvNgaylam.setVisibility(View.VISIBLE);
            }
            else
            {
                holder.imgDalam.setVisibility(View.INVISIBLE);
                holder.tvDiem.setVisibility(View.INVISIBLE);
                holder.tvNgaylam.setVisibility(View.INVISIBLE);
            }
            if(baingheSaved.contains(bainghe.getFilePath())){
                Log.d("ten bai nghe so sanh: ", bainghe.getFilePath());
                holder.imgSave.setVisibility(View.VISIBLE);
            }
            else   
                holder.imgSave.setVisibility(View.INVISIBLE);
            
            holder.stt.setText(bainghe.getStt());
            holder.tenbainghe.setText(bainghe.getTenBainghe());
            holder.llBox.setOnClickListener(new OnClickListener() {
                
                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub
                    //lay position cua item 
                    int which = -1;
                    Object obj =  v.getTag();                   
                    if(obj instanceof Integer){
                        which = ((Integer)obj).intValue();
                    }
                    if (which > -1) {
                        clickedIndex = which;
                    }
                    
                    View view = lv.getChildAt(clickedIndex - lv.getFirstVisiblePosition());
                    ImageButton imgSave = (ImageButton)view.findViewById(R.id.imgSave);
                    
                    //lay id bai nghe
                    String id = "";
                    Object id_obj = imgSave.getTag();
                    if(id_obj instanceof String){
                        id = id_obj.toString();
                    }
                    if (!id.equals("")) {
                        bookmark = id;
                    }                                       
                    bookmarkHandler();
                }
            });
            return row;
        }   
    }

    public static class BaingheHolder {
        TextView stt;
        TextView tenbainghe;
        TextView tvDiem;
        TextView tvNgaylam;
        ImageButton imgBookmark;
        ImageButton imgDalam;
        ImageButton imgSave;
        LinearLayout llBox;
    }
    class LoadBaiNghe extends AsyncTask<String, String, String> {
         
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            pDialog = new ProgressDialog(DsBaiNgheActivity.this);
            pDialog.setMessage("Đang tải danh sách bài nghe. Vui lòng đợi...");
            pDialog.setIndeterminate(false);
            pDialog.setCancelable(false);
            pDialog.show();
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters
            List<NameValuePair> paramsDSbainghe = new ArrayList<NameValuePair>();
            paramsDSbainghe.add(new BasicNameValuePair("capdo", capdo));
            
            List<NameValuePair> paramsUserdata = new ArrayList<NameValuePair>();
            paramsUserdata.add(new BasicNameValuePair("username", user.getUsername()));   
            Log.d("username: ", user.getUsername());
            JSONObject json = new JSONObject();
            String mes;
            // getting JSON string from URL
            try {
                //lay danh sach bai nghe
                json = jParser.makeHttpRequest(urlDsBainghe, "GET",
                        paramsDSbainghe);

                // Check your log cat for JSON reponse
                Log.d("DS bài nghe: ", json.toString());
                // Checking for SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    loadDsSuccess = true;
                    dsbainghe = json.getJSONArray(TAG_DSBAINGHE);
                    for (int i = 0; i < dsbainghe.length(); i++) {
                        JSONObject c = dsbainghe.getJSONObject(i);
                        BaiNghe temp = new BaiNghe(c.getString(TAG_ID), c.getString(TAG_STT), c.getString(TAG_CAPDO), 
                                c.getString(TAG_FILEPATH), c.getString(TAG_TENBAINGHE), null ,null ,null ,null);
                        baiNgheArraylist.add(temp);
                    }
                } 
                else 
                {
                    if(success==0 && mes.equals("No lesson found"))
                        noLessonFound = true;
                    else
                        if(success==0 && mes.equals("Can't connect to database"))
                            errorConnectDatabase = true;
                }
                //lay du lieu cua nguoi dung
                json = jParser.makeHttpRequest(urlUserData, "GET",
                        paramsUserdata);
                Log.d("Userdata: ", json.toString());
                // Check SUCCESS TAG
                success = json.getInt(TAG_SUCCESS);
                mes = json.getString(TAG_MESSAGE);
                if (success == 1 && mes.equals("OK")) {
                    JSONArray userdata = json.getJSONArray(TAG_USERDATA);
                    if(userdata.length()>0)
                    {
                        for (int i = 0; i < userdata.length(); i++) {
                            JSONObject c = userdata.getJSONObject(i);
    
                            // Storing each json item in variable
                            String bookmark = c.getString(TAG_BOOKMARK);
                            String dalam = c.getString(TAG_DALAM);
                            String diem = c.getString(TAG_DIEM);
                            String ngaylam = c.getString(TAG_NGAYLAM);
                            for (int j = 0; j < baiNgheArraylist.size(); j++) {
                                if (baiNgheArraylist.get(j).getId().equals(bookmark)) {
                                    baiNgheArraylist.get(j).setBookmark("yes");
                                }
                                if (baiNgheArraylist.get(j).getId().equals(dalam)) {
                                    baiNgheArraylist.get(j).setDaLam("yes");
                                    baiNgheArraylist.get(j).setDiem(diem);
                                    baiNgheArraylist.get(j).setNgayLam(ngaylam);
                                }
                            }
                        }
                    }                   
                }
                else if (success == 0 && mes.equals("Can't connect to database"))
                    errorConnectDatabase = true;

            } catch (Exception ex) {
                /*AlertDialog.Builder builder = new AlertDialog.Builder(
                        DsBaiNgheActivity.this);
                builder.setMessage(
                        "Không thể tải dữ liệu từ server. Xin hãy thử lại.")
                        .setCancelable(false)
                        .setTitle("Lỗi")
                        .setIcon(R.drawable.warning_icon)
                        .setPositiveButton("OK",
                                new DialogInterface.OnClickListener() {
                                    public void onClick(
                                            DialogInterface dialog, int id) {
                                        dialog.dismiss();
                                        finish();
                                    }
                                });
                AlertDialog alert = builder.create();
                alert.show();*/
            }
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // dismiss the dialog after getting all products
            pDialog.dismiss();
            if(loadDsSuccess)
            {
                loadDsSuccess = false;
                // updating UI from Background Thread
                runOnUiThread(new Runnable() {
                    public void run() {
                        BaingheAdapter adapter = new BaingheAdapter(getApplicationContext(), R.layout.bainghe_item, baiNgheArraylist);
                        lv.setClickable(true);
                        lv.setOnItemClickListener(new OnItemClickListener() {
                         
                            @Override
                            public void onItemClick(AdapterView<?> parent, View view,
                                    int position, long id) {
                                clickedIndex = position;
                                baiNghe = baiNgheArraylist.get(position);
                                filePath = baiNghe.getFilePath();
                                url = urlDownload + filePath;
                              //kiểm tra nếu bài nghe chưa có trong máy
                                if(!baingheTonTai(filePath)){
                                    AlertDialog.Builder builder = new AlertDialog.Builder(DsBaiNgheActivity.this);
                                    builder.setTitle("Thông báo")
                                           .setMessage("Bài nghe chưa có trong máy, bạn có muốn download về từ internet?")
                                           .setCancelable(false)
                                           .setIcon(R.drawable.download)
                                           .setPositiveButton("Có", new DialogInterface.OnClickListener() {
                                               public void onClick(DialogInterface dialog, int id) {
                                                    if (checkInternetConnection()) {                                            
                                                        //startDownload(url);
                                                        downloadHandler(url);
                                                   }
                                                   else
                                                   {
                                                       AlertDialog.Builder builder = new AlertDialog.Builder(DsBaiNgheActivity.this);
                                                        builder.setTitle("Lỗi")
                                                               .setMessage("Không có kết nối internet... Hãy thử lại sau.")
                                                               .setCancelable(false)
                                                               .setIcon(R.drawable.warning_icon)
                                                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                                                   public void onClick(DialogInterface dialog, int id) {
                                                                       dialog.dismiss();
                                                                   }
                                                               });
                                                        AlertDialog alert = builder.create();
                                                        alert.show();
                                                   }
                                               }
                                           })
                                           .setNegativeButton("Không",
                                                new DialogInterface.OnClickListener() {
                                                    public void onClick(DialogInterface dialog, int id) {
                                                           dialog.dismiss();
                                                    }
                                                }); 
                                    AlertDialog alert = builder.create();
                                    alert.show();
                                }
                                //bài nghe đã có trong máy
                                else
                                {
                                    // Starting new intent
                                    Intent in = new Intent(getApplicationContext(),
                                            NgheActivity.class);
                                    // sending data to next activity
                                    in.putExtra(TAG_FILEPATH, path + capdo + "/" + filePath);
                                    in.putExtra("bainghe", baiNghe);
                                    in.putExtra("userinfo", user);
                                    startActivity(in);
                                }
                                
                            }
                        });      
                        lv.setAdapter(adapter);
                    }
                });
            }
            else
                if(noLessonFound){
                    noLessonFound = false;
                    AlertDialog.Builder builder = new AlertDialog.Builder(DsBaiNgheActivity.this);
                    builder.setTitle("Thông báo")
                           .setMessage("Không tìm thấy bài nghe nào.")
                           .setCancelable(false)
                           .setIcon(R.drawable.warning_icon)
                           .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                               public void onClick(DialogInterface dialog, int id) {
                                   dialog.dismiss();
                               }
                           });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
                else
                    if(errorConnectDatabase){
                        errorConnectDatabase = false;
                        AlertDialog.Builder builder = new AlertDialog.Builder(DsBaiNgheActivity.this);
                        builder.setTitle("Lỗi")
                               .setMessage("Không thể kết nối đến database. Vui lòng thử lại sau.")
                               .setCancelable(false)
                               .setIcon(R.drawable.warning_icon)
                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {
                                       dialog.dismiss();
                                   }
                               });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
 
        }
    }
    //them/xoa bookmark
    class AddRemoveBookmark extends AsyncTask<String, String, String> {
         
        @Override
        protected void onPreExecute() {
            super.onPreExecute();            
        }
 
        protected String doInBackground(String... args) {
            // Building Parameters            
            List<NameValuePair> paramsAddbookmark = new ArrayList<NameValuePair>();
            paramsAddbookmark.add(new BasicNameValuePair("username", user.getUsername()));   
            paramsAddbookmark.add(new BasicNameValuePair("bainghe", bookmark)); 
            JSONObject json = new JSONObject();
            // getting JSON string from URL
            try {               
                //gui du lieu len server
                json = jParser.makeHttpRequest(urlAddRemoveBookmark, "POST",
                        paramsAddbookmark);
                Log.d("bookmark: ", json.toString());
                // Check SUCCESS TAG
                int success = json.getInt(TAG_SUCCESS);
                String mes = json.getString("message");
                if (success == 1 && mes.equals("Inserted")) {
                    insertedBookmarkSuccess = true;
                }
                else
                    if (success == 1 && mes.equals("Deleted")) {
                        deletedBookmarkSuccess = true;
                    }
                    else
                    {
                        errorConnectDatabase = true;
                    }   
            } 
            catch (Exception ex) {
                Toast.makeText(getApplicationContext(), "Có lỗi xảy ra. " + ex.toString(), Toast.LENGTH_SHORT).show();
            }
            return null;
        }
         
        protected void onPostExecute(String file_url) {
            // updating UI from Background Thread
            if(insertedBookmarkSuccess){
                insertedBookmarkSuccess = false;
                View v = lv.getChildAt(clickedIndex - lv.getFirstVisiblePosition());
                ImageButton imgbookmark = (ImageButton)v.findViewById(R.id.imgBookmark);
                imgbookmark.setBackgroundResource(R.drawable.bookmarked);
                Toast.makeText(getApplicationContext(), "Đã bookmark bài nghe", Toast.LENGTH_SHORT).show();
            }
            else 
                if(deletedBookmarkSuccess){
                    deletedBookmarkSuccess = false;
                    View v = lv.getChildAt(clickedIndex - lv.getFirstVisiblePosition());
                    ImageButton imgbookmark = (ImageButton)v.findViewById(R.id.imgBookmark);
                    imgbookmark.setBackgroundResource(R.drawable.none_bookmark);
                    Toast.makeText(getApplicationContext(), "Đã xóa bookmark bài nghe", Toast.LENGTH_SHORT).show();
                }
                else 
                    if(errorConnectDatabase){
                        errorConnectDatabase = false;
                        AlertDialog.Builder builder = new AlertDialog.Builder(DsBaiNgheActivity.this);
                        builder.setTitle("Lỗi")
                               .setMessage("Không thể kết nối đến database. Vui lòng thử lại sau.")
                               .setCancelable(false)
                               .setIcon(R.drawable.warning_icon)
                               .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                                   public void onClick(DialogInterface dialog, int id) {
                                       dialog.dismiss();
                                   }
                               });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }
        }
    }
    public void bookmarkHandler(){              
        final AddRemoveBookmark ar_bm = new AddRemoveBookmark();
        ar_bm.execute();    
        Handler _handler = new Handler();
        _handler.postDelayed(new Runnable() {
            @Override
            public void run() {
                if (ar_bm.getStatus() == AsyncTask.Status.RUNNING) {
                    ar_bm.cancel(true);
                    pDialog.dismiss();
                    AlertDialog.Builder builder = new AlertDialog.Builder(
                            DsBaiNgheActivity.this);
                    builder.setMessage(
                            "Không thể kết nối đến server. Xin hãy thử lại.")
                            .setCancelable(false)
                            .setTitle("Lỗi")
                            .setIcon(R.drawable.warning_icon)
                            .setPositiveButton("OK",
                                    new DialogInterface.OnClickListener() {
                                        public void onClick(
                                                DialogInterface dialog, int id) {
                                            dialog.dismiss();
                                        }
                                    });
                    AlertDialog alert = builder.create();
                    alert.show();
                }
            }
        }, 30000); // timeout sau ... giây sẽ hiện thông báo không kết nối được.
    }
    public void loadBaingheHandler(){
        final LoadBaiNghe loadds = new LoadBaiNghe();        
        try{            
            loadds.execute();
            Handler _handler = new Handler();
            _handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (loadds.getStatus() == AsyncTask.Status.RUNNING) {
                        loadds.cancel(true);
                        pDialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                DsBaiNgheActivity.this);
                        builder.setMessage(
                                "Kết nối quá thời gian... Xin hãy thử lại.")
                                .setCancelable(false)
                                .setIcon(R.drawable.warning_icon)
                                .setTitle("Lỗi")
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int id) {
                                                dialog.dismiss();
                                                finish();
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }

                }
            }, 30000); // timeout sau...giây sẽ hiện thông báo không kết nối
                        // được.
        }
        catch (Exception ex)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DsBaiNgheActivity.this);
            builder.setMessage(
                    "Không thể tải dữ liệu từ server. Xin hãy thử lại.")
                    .setCancelable(false)
                    .setTitle("Lỗi")
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }       
    }
    public void downloadHandler(String url){
        final DownloadFileAsync download = new DownloadFileAsync();        
        try{            
            download.execute(url);
            Handler _handler = new Handler();
            _handler.postDelayed(new Runnable() {
                @Override
                public void run() {
                    if (download.getStatus() == AsyncTask.Status.RUNNING) {
                        download.cancel(true);
                        pDialog.dismiss();
                        AlertDialog.Builder builder = new AlertDialog.Builder(
                                DsBaiNgheActivity.this);
                        builder.setMessage(
                                "Kết nối quá thời gian... Xin hãy thử lại.")
                                .setCancelable(false)
                                .setIcon(R.drawable.warning_icon)
                                .setTitle("Lỗi")
                                .setPositiveButton("OK",
                                        new DialogInterface.OnClickListener() {
                                            public void onClick(
                                                    DialogInterface dialog,
                                                    int id) {
                                                dialog.dismiss();
                                                finish();
                                            }
                                        });
                        AlertDialog alert = builder.create();
                        alert.show();
                    }

                }
            }, 180000); // timeout sau 3 phút sẽ hiện thông báo không kết nối
                        // được.
        }
        catch (Exception ex)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(
                    DsBaiNgheActivity.this);
            builder.setMessage(
                    "Không thể tải dữ liệu từ server. Xin hãy thử lại.")
                    .setCancelable(false)
                    .setTitle("Lỗi")
                    .setIcon(R.drawable.warning_icon)
                    .setPositiveButton("OK",
                            new DialogInterface.OnClickListener() {
                                public void onClick(
                                        DialogInterface dialog,
                                        int id) {
                                    dialog.dismiss();
                                }
                            });
            AlertDialog alert = builder.create();
            alert.show();
        }       
    }
}

